package visual

import (
	"bytes"
	"cgs-server/helper"
	"cgs-server/internal/cgserver/embedfile"
	"cgs-server/server"
	"cgs-server/server/assets/cgs"
	"cgs-server/server/assets/cgs_bim"
	"cgs-server/server/assets/cgs_map"
	"cgs-server/server/assets/cgs_portal"
	"cgs-server/server/assets/earth"
	"cgs-server/server/assets/scene"
	"cgs-server/server/base"
	"cgs-server/server/model"
	"fmt"
	"go.mongodb.org/mongo-driver/bson"
	"go.mongodb.org/mongo-driver/bson/primitive"
	"io/ioutil"
	"mime/multipart"
	"net/http"
	"strconv"
	"strings"
	"text/template"
)

func init() {
	//server.Handle(http.MethodGet, "/api/Cgs/Portal/Export", ExportVisual, server.None)
	//server.Handle(http.MethodPost, "/api/Cgs/Portal/Import", ImportVisual, server.None)
	//server.Handle(http.MethodGet, "/api/Cgs/Portal/Cascade", Cascade, server.None)

	server.Get("/api/Cgs/Portal/Export", ExportVisual, "导出应用", server.Login)
	server.Post("/api/Cgs/Portal/Import", ImportVisual, "导入应用", server.Import)
	server.Get("/api/Cgs/Portal/Cascade", Cascade, "应用分类信息", server.Login)

	server.Post("/api/Cgs/Portal/Visual/Add", AddVisual, "添加应用", server.Login)
	server.Post("/api/Cgs/Portal/Visual/Edit", Edit, "更新应用", server.Login)
	server.Post("/api/Cgs/Portal/Visual/Delete", Delete, "删除应用", server.Login)
	server.Post("/api/Cgs/Portal/Visual/PutFile", PutFile, "上传文件(server)", server.Login)
	server.Get("/api/Cgs/Portal/Visual/Detail", Detail, "获取应用详情", server.Login)
	server.Get("/api/Cgs/Portal/Visual/GetByProjectID", GetByProjectID, "根据projectID获取应用详情", server.Login)
	server.Get("/api/Cgs/Portal/Visual/checkPreviewPermission", checkPreviewPermission, "检查预览页面的权限", server.None)
	server.Get("/api/Cgs/Portal/Visual/List", List, "获取应用列表", server.Login)
	server.Get("/api/Cgs/Portal/Visual/ListAll", ListAll, "获取当前用户应用列表", server.Login)

	server.Post("/api/Cgs/Portal/Check", Check, "检查应用角色", server.Login)
}

func ExportVisual(w http.ResponseWriter, r *http.Request) {
	visualId, err := primitive.ObjectIDFromHex(r.FormValue("visualId"))
	visualType := r.FormValue("visualType")
	if err != nil {
		_, _ = helper.WriteJSON(w, server.CgsResult{
			Code: 300,
			Msg:  err.Error(),
		})
	}
	if visualType == "" {
		_, _ = helper.WriteJSON(w, server.CgsResult{
			Code: 300,
			Msg:  "VisualType is required.",
		})
	}

	user, _ := server.GetCurrentUser(r)

	visualService := NewVisualService()
	zipData, err := visualService.Export(visualId, visualType, user)
	if err != nil {
		_, _ = helper.WriteJSON(w, server.CgsResult{
			Code: 300,
			Msg:  err.Error(),
		})
		return
	}

	buf, err := base.ZipFile(zipData)
	if err != nil {
		_, _ = helper.WriteJSON(w, server.CgsResult{
			Code: 300,
			Msg:  err.Error(),
		})
		return
	}
	head := w.Header()
	head.Set("Content-Disposition", "attachment; filename=CGS.zip")
	n, _ := buf.WriteTo(w)

	fmt.Println("字节数：", n)

}

func ImportVisual(w http.ResponseWriter, r *http.Request) {
	_ = r.ParseMultipartForm(100 << 20)
	var file *multipart.FileHeader
	files := r.MultipartForm.File
	if f, ok := files["file"]; ok {
		if len(f) > 0 {
			file = f[0]
		}
	}
	classify := r.FormValue("category")
	visualType := r.FormValue("visualType")
	filePath := r.FormValue("filePath")
	if visualType == "" {
		visualType = string(cgs_portal.ThreeD)
	}

	user, _ := base.GetCurrentUser(r)
	if user == nil {
		_, _ = helper.WriteJSON(w, server.Fail("Permission denied."))
	}

	serverHost := fmt.Sprintf("http://%s%s", strings.Split(r.Host, ":")[0], ":2020")

	visualService := NewVisualService()
	err := visualService.Import(file, filePath, classify, visualType, serverHost, user)

	if err != nil {
		_, _ = helper.WriteJSON(w, server.Fail(err.Error()))
		return
	}
	_, _ = helper.WriteJSON(w, server.OK("Import successfully."))
}

func TraverseZipFileData(zipData []*model.ZipFileData) bson.A {
	dataArr := bson.A{}

	for _, value := range zipData {
		var dataMap = make(map[string]interface{})
		dataMap["name"] = value.Name
		var result interface{}
		err := helper.FromJSON(value.Body, &result)
		if err != nil {
			dataMap["data"] = value.Body
		} else {
			dataMap["data"] = &result
		}
		dataArr = append(dataArr, dataMap)
	}

	return dataArr
}

// 级联选择器使用
func Cascade(w http.ResponseWriter, r *http.Request) {
	user, err := base.GetCurrentUser(r)
	if err != nil {
		_, _ = helper.WriteJSON(w, server.Fail(err.Error()))
		return
	}
	_ = r.ParseForm()
	visualTypes := r.Form["visualType"]
	if len(visualTypes) == 0 {
		visualTypes = append(visualTypes, "ThreeD", "TwoD", "Earth", "Bim", "App")
	}
	vm := map[string]string{"ThreeD": "三维", "TwoD": "二维", "Earth": "Earth", "Bim": "BIM", "App": "App"}
	getAllWorksheet := r.FormValue("getAllWorksheet") == "true"

	visualService := NewVisualService()

	if len(visualTypes) > 1 {
		var res []*VisualCascade
		for _, s := range visualTypes {
			result, err := visualService.Cascade(s, getAllWorksheet, user)
			if err != nil {
				_, _ = helper.WriteJSON(w, server.Fail(err.Error()))
				return
			}
			if len(result) > 0 {
				res = append(res, &VisualCascade{
					Value:    s,
					Label:    vm[s],
					Children: result,
				})
			}
		}
		_, _ = helper.WriteJSON(w, server.OK("Get successfully!").WithData(res))
	} else {
		result, err := visualService.Cascade(visualTypes[0], getAllWorksheet, user)
		if err != nil {
			_, _ = helper.WriteJSON(w, server.Fail(err.Error()))
			return
		}
		_, _ = helper.WriteJSON(w, server.CgsResult{
			Code:    200,
			Msg:     "Get successfully!",
			Data:    result,
			Success: true,
		})
	}
}

// 添加应用
func AddVisual(w http.ResponseWriter, r *http.Request) {
	r.Body = http.MaxBytesReader(w, r.Body, int64(100<<20))
	s, _ := ioutil.ReadAll(r.Body) //把  body 内容读入字符串 s

	mdl := &Model{}
	err := helper.FromJSON(s, mdl)
	if err != nil {
		_, _ = helper.WriteJSON(w, server.Fail(err.Error()))
		return
	}

	title := strings.TrimSpace(mdl.Visual.Title)
	if title == "" || strings.HasPrefix(title, "_") {
		_, _ = helper.WriteJSON(w, server.Fail("Title is not allowed to be empty or start with _."))
		return
	}

	duModel := base.GenerateDataUserModel(mdl, r)

	// 创建visualID
	mdl.Visual.ID = primitive.NewObjectID()

	// 场景数据中的 server 值
	serverHost := fmt.Sprintf("http://%s%s", strings.Split(r.Host, ":")[0], server.Config.Server.Port)

	addSceneModel := scene.Model{}
	addSceneModel.Name = title

	user, _ := server.GetCurrentUser(r)

	if server.Config.Authority.Enabled {
		if user == nil {
			_, _ = helper.WriteJSON(w, server.Result{
				Code: 300,
				Msg:  "Permission denied.",
			})
			return
		}
	}

	if user != nil {
		mdl.Visual.UserId = user.ID
		mdl.Config.UserId = user.ID
		addSceneModel.UserId = user.ID
	}

	if mdl.IsPortal {
		// 从门户创建，需要添加空场景和cgsProject, 返回 ProjectID
		if mdl.VisualType == "ThreeD" {
			result := AddSceneAndCgsProject(&addSceneModel, mdl.Visual.ID.Hex(), serverHost, duModel.User)
			if result.Error != nil {
				_, _ = helper.WriteJSON(w, server.Result{
					Code: 300,
					Msg:  result.Error.Error(),
				})
				return
			}
			//projId, _ := primitive.ObjectIDFromHex(result.NodeId)
			mdl.Visual.ProjectID = result.Id
		}
		if mdl.VisualType == "Earth" {
			earthModel := earth.Earth{}
			earthModel.Name = title
			earthModel.UserId = duModel.User.GetUserId()
			result := AddGlobeAndCgsGlobeProject(&earthModel, mdl.Visual.ID.Hex(), duModel.User, mdl.VisualType)
			if result.Error != nil {
				_, _ = helper.WriteJSON(w, server.Result{
					Code: 300,
					Msg:  result.Error.Error(),
				})
				return
			}
			//projId, _ := primitive.ObjectIDFromHex(result.NodeId)
			mdl.Visual.ProjectID = result.Id
		}
		if mdl.VisualType == "TwoD" {
			cgsMap := cgs_map.CgsMap{
				Name: title,
			}
			cgsMap.UserId = duModel.User.GetUserId()
			result := addTwoDAndCgsProject(&cgsMap, mdl.Visual.ID.Hex(), duModel.User, mdl.VisualType)
			if result.Error != nil {
				_, _ = helper.WriteJSON(w, server.Result{
					Code: 300,
					Msg:  result.Error.Error(),
				})
				return
			}
			mdl.Visual.ProjectID = result.Id
		}
		if mdl.VisualType == "Bim" {
			bimModel := cgs_bim.Bim{}
			bimModel.Name = title
			bimModel.UserId = duModel.User.GetUserId()
			result := addBimAndBimProject(&bimModel, mdl.Visual.ID.Hex(), duModel.User, mdl.VisualType)
			if result.Error != nil {
				_, _ = helper.WriteJSON(w, server.Result{
					Code: 300,
					Msg:  result.Error.Error(),
				})
				return
			}
			//projId, _ := primitive.ObjectIDFromHex(result.NodeId)
			mdl.Visual.ProjectID = result.Id
		}
	}

	visualService := NewVisualService()
	err = visualService.Add(duModel)

	if err != nil {
		_, _ = helper.WriteJSON(w, server.Fail(err.Error()))
		return
	}

	_, _ = helper.WriteJSON(w, server.OK("Add successfully.").WithData(bson.M{
		"id": mdl.Visual.ID, // result 也可以拿到新增的 id
	}))
}

// 添加 Editor 空场景和 CgsProject 工程
func AddSceneAndCgsProject(sceneModel *scene.Model, publishID string, serverHost string, user *model.User) *base.AddResult {
	/*----------------------AddScene-------------------------*/
	// name, data
	// 读取空场景文件 scene.json
	savePath := "template/data/scene.json"

	//if _, err := os.Stat(savePath); os.IsNotExist(err) {
	//	return &base.AddResult{Error: err}
	//}
	//// 读取空场景文件
	//file, err := os.Open(savePath)
	//if err != nil {
	//	return &base.AddResult{Error: err}
	//}
	//defer file.Close()
	//
	//fd, err := ioutil.ReadAll(file)
	//if err != nil {
	//	return &base.AddResult{Error: err}
	//}

	// 从 embed 中读取模版文件
	fd, err := embedfile.Template.ReadFile(savePath)
	if err != nil {
		return &base.AddResult{Error: err}
	}

	var list []interface{}
	err = bson.UnmarshalExtJSON(fd, false, &list)
	if err != nil {
		return &base.AddResult{Error: err}
	}

	docs := []interface{}{}
	for _, v := range list {
		dataMap := v.(primitive.D).Map()
		if _, ok := dataMap["server"]; ok {
			dataMap["server"] = serverHost
		}
		docs = append(docs, dataMap)
	}
	sceneModel.DataArr = docs

	// 新增场景数据
	sceneService := scene.NewSceneService()
	err = sceneService.Save(&model.DataUserModel{
		Data: sceneModel,
		User: user,
	})
	if err != nil {
		return nil
	}

	templatePath := "template/data/CgsProjectTemplate.js"
	return addCgsProject(sceneModel.Name, "", publishID, sceneModel.ID.Hex(), templatePath, user)
}

// 添加 Globe 空场景和 CgsGlobeProject 工程
func AddGlobeAndCgsGlobeProject(earthModel *earth.Earth, publishID string, user *model.User, visualType string) *base.AddResult {
	/*----------------------AddScene-------------------------*/
	// name, data

	// 新增场景数据
	earthService := earth.NewEarthService()
	err := earthService.Save(&model.DataUserModel{
		Data: earthModel,
		User: user,
	})
	if err != nil {
		return nil
	}

	templatePath := "template/data/CgsGlobeProjectTemplate.js"
	return addCgsProject(earthModel.Name, visualType, publishID, earthModel.ID.Hex(), templatePath, user)
}

// 添加 Globe 空场景和 CgsGlobeProject 工程
func addBimAndBimProject(bimModel *cgs_bim.Bim, publishID string, user *model.User, visualType string) *base.AddResult {
	/*----------------------AddScene-------------------------*/
	// name, data

	// 新增场景数据
	bimService := cgs_bim.NewBimService()
	err := bimService.Save(&model.DataUserModel{
		Data: bimModel,
		User: user,
	})
	if err != nil {
		return nil
	}

	templatePath := "template/data/CgsBimProjectTemplate.js"
	return addCgsProject(bimModel.Name, visualType, publishID, bimModel.ID.Hex(), templatePath, user)
}

func addTwoDAndCgsProject(cgsMap *cgs_map.CgsMap, publishID string, user *model.User, visualType string) *base.AddResult {
	// add scene
	cgsMapService := cgs_map.NewMapService()
	err := cgsMapService.Save(&model.DataUserModel{
		Data: cgsMap,
		User: user,
	})
	if err != nil {
		return nil
	}

	templatePath := "template/data/CgsMapProjectTemplate.js"
	return addCgsProject(cgsMap.Name, visualType, publishID, cgsMap.Id.Hex(), templatePath, user)
}

// addCgsProject 添加 cgs project
func addCgsProject(name, visualType, publishID, sceneId, templatePath string, user *model.User) *base.AddResult {
	cgsModel := &cgs.CgsProj{}
	cgsModel.Name = name
	cgsModel.Type = visualType
	cgsModel.Public = new(bool)
	cgsModel.UserId = user.GetUserId()
	cgsModel.PublishId = publishID
	cgsModel.SceneId = sceneId

	// jsData, 从模板文件中读取
	//if _, err := os.Stat(templatePath); os.IsNotExist(err) {
	//	return &base.AddResult{Error: err}
	//}
	//t, err := template.ParseFiles(templatePath)

	t, err := template.ParseFS(embedfile.Template, templatePath)
	if err != nil {
		return &base.AddResult{Error: err}
	}
	config := cgs.CgsProjectConfig{
		SceneID: sceneId,
		AppID:   publishID,
	}
	var b bytes.Buffer
	err = t.Execute(&b, config) // 替换模板中的数据
	if err != nil {
		return &base.AddResult{Error: err}
	}
	cgsModel.Data = b.String() // 模板转换后的 js 数据

	cgsService := cgs.NewCgsService()
	err = cgsService.Save(&model.DataUserModel{
		Data: cgsModel,
		User: user,
	})
	return &base.AddResult{
		Id:    cgsModel.ID.Hex(),
		Error: err,
	}
}

// 更新应用
func Edit(w http.ResponseWriter, r *http.Request) {
	r.Body = http.MaxBytesReader(w, r.Body, int64(100<<20))
	s, _ := ioutil.ReadAll(r.Body) //把  body 内容读入字符串 s
	mdl := &Model{}

	err := helper.FromJSON(s, mdl)
	if err != nil {
		_, _ = helper.WriteJSON(w, server.Fail(err.Error()))
		return
	}

	if mdl.VisualType == "" {
		_, _ = helper.WriteJSON(w, server.Fail("VisualType is not allowed empty!"))
		return
	}
	if _, ok := cgs_portal.VisualTypes[mdl.VisualType]; !ok {
		_, _ = helper.WriteJSON(w, server.Fail("VisualType is not existed."))
		return
	}

	duModel := base.GenerateDataUserModel(mdl, r)
	visualService := NewVisualService()
	err = visualService.Update(duModel)
	if err != nil {
		_, _ = helper.WriteJSON(w, server.Fail(err.Error()))
		return
	}
	_, _ = helper.WriteJSON(w, server.OK("Update successfully!"))
}

// 删除应用
func Delete(w http.ResponseWriter, r *http.Request) {
	id, err := primitive.ObjectIDFromHex(strings.TrimSpace(r.FormValue("ID")))
	if err != nil {
		_, _ = helper.WriteJSON(w, server.Fail("ID is not allowed to be empty."))
		return
	}

	visualType := strings.TrimSpace(r.FormValue("VisualType"))

	if visualType == "" {
		_, _ = helper.WriteJSON(w, server.Fail("VisualType is not allowed empty!"))
		return
	}
	if _, ok := cgs_portal.VisualTypes[visualType]; !ok {
		_, _ = helper.WriteJSON(w, server.Fail("VisualType is not existed."))
		return
	}

	duModel := base.GenerateDataUserModel(&Model{
		Visual:     Visual{ID: id},
		Config:     Config{VisualId: id},
		VisualType: visualType,
	}, r)
	visualService := NewVisualService()
	err = visualService.Remove(duModel)
	if err != nil {
		_, _ = helper.WriteJSON(w, server.Fail(err.Error()))
		return
	}
	_, _ = helper.WriteJSON(w, server.OK("Delete successfully!"))
}

// 上传文件
func PutFile(w http.ResponseWriter, r *http.Request) {
	_ = r.ParseMultipartForm(server.Config.Upload.MaxSize)
	files := r.MultipartForm.File

	// check upload file
	if len(files) != 1 {
		_, _ = helper.WriteJSON(w, server.Result{
			Code: 300,
			Msg:  "Please select an file.",
		})
		return
	}
	file := files["file"][0]

	duModel := base.GenerateDataUserModel(nil, r)
	visualService := NewVisualService()
	result, err := visualService.PutFileToServer(file, duModel)
	if err != nil {
		_, _ = helper.WriteJSON(w, server.Fail(err.Error()))
		return
	}
	_, _ = helper.WriteJSON(w, server.OK("Upload successfully!").WithData(result))
}

// 获取视图详情
func Detail(w http.ResponseWriter, r *http.Request) {
	visualType := strings.TrimSpace(r.FormValue("VisualType"))
	if visualType == "" {
		_, _ = helper.WriteJSON(w, server.Fail("VisualType is not allowed empty!"))
		return
	}
	if _, ok := cgs_portal.VisualTypes[visualType]; !ok {
		_, _ = helper.WriteJSON(w, server.Fail("VisualType is not existed."))
		return
	}
	// id
	visualId, err := primitive.ObjectIDFromHex(strings.TrimSpace(r.FormValue("ID")))
	if err != nil {
		_, _ = helper.WriteJSON(w, server.Fail("ID is not allowed to be empty."))
		return
	}

	mdl := &Model{
		Visual:     Visual{ID: visualId},
		Config:     Config{VisualId: visualId},
		VisualType: visualType,
	}
	duModel := base.GenerateDataUserModel(mdl, r)
	visualService := NewVisualService()
	res, err := visualService.GetOne(duModel)
	if err != nil {
		_, _ = helper.WriteJSON(w, server.Fail(err.Error()))
		return
	}
	_, _ = helper.WriteJSON(w, server.OK("Get successfully!").WithData(res))
}

func GetByProjectID(w http.ResponseWriter, r *http.Request) {
	visualType := strings.TrimSpace(r.FormValue("VisualType"))
	if visualType == "" {
		_, _ = helper.WriteJSON(w, server.Fail("VisualType is not allowed empty!"))
		return
	}
	if _, ok := cgs_portal.VisualTypes[visualType]; !ok {
		_, _ = helper.WriteJSON(w, server.Fail("VisualType is not existed."))
		return
	}
	// id
	projectID := r.FormValue("projectID")
	if projectID == "" {
		_, _ = helper.WriteJSON(w, server.Fail("projectID is not allowed to be empty."))
		return
	}

	mdl := &Model{
		Visual:     Visual{ProjectID: projectID},
		VisualType: visualType,
	}
	duModel := base.GenerateDataUserModel(mdl, r)
	visualService := NewVisualService()
	res, err := visualService.GetByProjectID(duModel)
	if err != nil {
		_, _ = helper.WriteJSON(w, server.Fail(err.Error()))
		return
	}
	_, _ = helper.WriteJSON(w, server.OK("Get successfully!").WithData(res))
}

func checkPreviewPermission(w http.ResponseWriter, r *http.Request) {
	visualType := strings.TrimSpace(r.FormValue("VisualType"))
	if visualType == "" {
		_, _ = helper.WriteJSON(w, server.Fail("VisualType is not allowed empty!"))
		return
	}
	if _, ok := cgs_portal.VisualTypes[visualType]; !ok {
		_, _ = helper.WriteJSON(w, server.Fail("VisualType is not existed."))
		return
	}
	// id
	projectID := r.FormValue("projectID")
	if projectID == "" {
		_, _ = helper.WriteJSON(w, server.Fail("projectID is not allowed to be empty."))
		return
	}

	mdl := &Model{
		Visual:     Visual{ProjectID: projectID},
		VisualType: visualType,
	}
	duModel := base.GenerateDataUserModel(mdl, r)
	visualService := NewVisualService()
	res, err := visualService.GetByProjectID(duModel)
	if err != nil {
		_, _ = helper.WriteJSON(w, server.Fail(err.Error()))
		return
	}

	modelRes := res.(*Model)

	if modelRes.Visual.ID.IsZero() {
		_, _ = helper.WriteJSON(w, server.OK("Get successfully!").WithData(bson.M{"hasPermission": false}))
		return
	}

	if *modelRes.Visual.Status == 0 { // 0 是未发布
		// 检查权限
		if duModel.User == nil {
			_, _ = helper.WriteJSON(w, server.OK("Get successfully!").WithData(bson.M{"hasPermission": false}))
		}

		if duModel.User.HasVisualAuth(modelRes.Visual.ID.Hex()) {
			_, _ = helper.WriteJSON(w, server.OK("Get successfully!").WithData(bson.M{"hasPermission": true}))
		} else {
			_, _ = helper.WriteJSON(w, server.OK("Get successfully!").WithData(bson.M{"hasPermission": false}))
		}
	} else {
		_, _ = helper.WriteJSON(w, server.OK("Get successfully!").WithData(bson.M{"hasPermission": true}))
	}
}

// 视图列表
func List(w http.ResponseWriter, r *http.Request) {
	visualType := strings.TrimSpace(r.FormValue("VisualType"))
	orgCategory := strings.TrimSpace(r.FormValue("orgCategory"))
	//if visualType == "" {
	//	_, _ = helper.WriteJSON(w, server.Fail("VisualType is not allowed empty!"))
	//	return
	//}
	if _, ok := cgs_portal.VisualTypes[visualType]; !ok {
		_, _ = helper.WriteJSON(w, server.Fail("VisualType is not existed."))
		return
	}
	// 分类
	var category2 = new(int32)
	if r.FormValue("Category") == "default" {
		*category2 = -1
	} else {
		category, err := strconv.ParseInt(r.FormValue("Category"), 10, 64)
		if err != nil {
			category2 = nil
		} else {
			*category2 = int32(category)
		}
	}
	var orgCate = new(int32)
	c, err := strconv.ParseInt(orgCategory, 10, 64)
	if err != nil {
		orgCate = nil
	} else {
		*orgCate = int32(c)
	}

	// 分页
	current, err := strconv.ParseInt(r.FormValue("Current"), 10, 64)
	if err != nil {
		current = 0
	}
	size, err := strconv.ParseInt(r.FormValue("Size"), 10, 64)
	if err != nil {
		size = 0
	}

	mdl := &Model{
		Visual:     Visual{Category: category2, OrgCategory: orgCate},
		VisualType: visualType,
	}
	duModel := base.GenerateDataUserModel(mdl, r)
	duModel.Page = &model.Page{
		Current: current,
		Size:    size,
	}
	visualService := NewVisualService()
	res, err := visualService.List(duModel)
	if err != nil {
		_, _ = helper.WriteJSON(w, server.Fail(err.Error()))
		return
	}
	_, _ = helper.WriteJSON(w, server.OK("Get Successfully!").WithData(res))
}

func ListAll(w http.ResponseWriter, r *http.Request) {
	user, err := base.GetCurrentUser(r)
	if err != nil {
		_, _ = helper.WriteJSON(w, server.Fail(err.Error()))
		return
	}

	visualService := NewVisualService()
	all, err := visualService.ListAll(user)
	if err != nil {
		_, _ = helper.WriteJSON(w, server.Fail(err.Error()))
		return
	}

	_, _ = helper.WriteJSON(w, server.OK("Get Successfully!").WithData(all))
}

func Check(w http.ResponseWriter, r *http.Request) {
	user, err := base.GetCurrentUser(r)
	if err != nil {
		helper.WriteJSON(w, server.Fail("Permission denied"))
		return
	}
	visualService := NewVisualService()
	err = visualService.CheckVisual(user)
	if err != nil {
		helper.WriteJSON(w, server.Fail(err.Error()))
		return
	}
	helper.WriteJSON(w, server.OK("Check successfully!"))
}
